package indie.lunker.shareit;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.MediaColumns;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ShareActivity extends Activity {
	private TextView mTxvProgressText = null;
	private ProgressBar mPgbProgressBar = null;
	private final String CACHE_FOLDER_NAME = ".shareit_cache";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_share);
		setTitle(R.string.title);
		
		mTxvProgressText = (TextView) findViewById(R.id.progressText);
		mPgbProgressBar = (ProgressBar) findViewById(R.id.progressBar);
		
		new ShareTask().execute();
	}
	
	private boolean checkCache() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			File cacheDir = new File(
					Environment.getExternalStorageDirectory(), 
					CACHE_FOLDER_NAME);
			
			if (!cacheDir.exists()) {
				cacheDir.mkdirs();
			}
			
			return true;
		} else {
			return false;
		}
	}
	
	private void clearCache () {
		if (checkCache() == true) {
			File cacheDir = new File(
					Environment.getExternalStorageDirectory(), 
					CACHE_FOLDER_NAME);
			File[] f = cacheDir.listFiles();
			
			if (f != null) {
				for (int i = 0; i < f.length; i++) {
					f[i].delete();
				}
			}
		}
	}
	
	private class ShareTask extends AsyncTask<Void, Integer, Integer> {
		private final int RET_OK = 100;
		private final int RET_FILE_NOT_FOUND = 200;
		private final int RET_ERROR_CACHING_FILE = 210;
		private final int RET_NO_SDCARD = 220;
		private boolean canceled = false;
		private String filename = null;
		private long filesize = 0;
		private File cacheFile = null;
		private InputStream in = null;
		private FileOutputStream out = null;
		private Intent sendIt = new Intent(Intent.ACTION_SEND);

		@Override
		protected void onPreExecute() {
			mPgbProgressBar.setMax(100);
			mPgbProgressBar.setProgress(0);
			mTxvProgressText.setText("0%");
			
			if (checkCache() == false) {
				this.cancel(true);
			}
		}

		@Override
		protected Integer doInBackground(Void... params) {
			String stateStr = Environment.getExternalStorageState();
			
			if (!stateStr.equals(Environment.MEDIA_MOUNTED)) {
				return RET_NO_SDCARD;
			}
			
			clearCache();
			Intent fileIt = getIntent();
			System.out.println(">>>>> Mime-type: " + fileIt.getType());
			sendIt.setType(fileIt.getType());
			
			if (fileIt.getScheme().equals("content")) {
				System.out.println(">>>>> Uri: " + fileIt.getData().toString());
				Cursor c = getContentResolver().query(
						fileIt.getData(), 
						null, 
						null, 
						null, 
						null);
				c.moveToFirst();
				filename = c.getString(c.getColumnIndex(MediaColumns.DISPLAY_NAME));
				filesize = c.getLong(c.getColumnIndex(MediaColumns.SIZE));
				c.close();
				cacheFile = new File(
						new File(
								Environment.getExternalStorageDirectory(),
								CACHE_FOLDER_NAME),
						filename);
				
				try {
					in = getContentResolver().openInputStream(fileIt.getData());
					cacheFile.createNewFile();
					out = new FileOutputStream(cacheFile);
					
					byte[] buff = new byte[8192];
					int count = 0;
					long sum = 0;
					
					while ((count = in.read(buff)) != -1 && !canceled) {
						out.write(buff, 0, count);
						sum += count;
						publishProgress(Long.valueOf(sum / filesize).intValue());
					}
				} catch (FileNotFoundException e) {
					return Integer.valueOf(RET_FILE_NOT_FOUND);
				} catch (IOException e) {
					return Integer.valueOf(RET_ERROR_CACHING_FILE);
				} finally {
					if (in != null) {
						try {
							in.close();
						} catch (IOException e) {
						}
					}
					
					if (out != null) {
						try {
							out.close();
						} catch (IOException e) {
						}
					}
				}
				
				sendIt.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(cacheFile));
			} else if (fileIt.getScheme().equals("file")) {
				sendIt.putExtra(Intent.EXTRA_STREAM, fileIt.getData());
			}
			
			return RET_OK;
		}

		@Override
		protected void onCancelled() {
			canceled = true;
		}

		@Override
		protected void onPostExecute(Integer result) {
			switch (result.intValue()) {
			case RET_OK:
				if (!canceled) {
					startActivity(Intent.createChooser(sendIt, getString(R.string.share)));
				}
				break;
			case RET_FILE_NOT_FOUND:
				Toast.makeText(
						ShareActivity.this,
						R.string.file_not_found,
						Toast.LENGTH_SHORT).show();
				break;
			case RET_ERROR_CACHING_FILE:
				Toast.makeText(
						ShareActivity.this,
						R.string.error_caching_file,
						Toast.LENGTH_SHORT).show();
				break;
			case RET_NO_SDCARD:
				Toast.makeText(
						ShareActivity.this,
						R.string.need_sdcard,
						Toast.LENGTH_SHORT).show();
				break;
			}
			
			finish();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			int value = values[0].intValue();
			mTxvProgressText.setText(value + "%");
			mPgbProgressBar.setProgress(value);
		}
		
	}
}
